package actions.xml;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.sql.SQLException;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import org.apache.tools.ant.types.selectors.TypeSelector.FileType;

import persistencia.JAXBAgent;

import com.google.appengine.api.datastore.Blob;
import com.opensymphony.xwork2.ActionSupport;

import dominio.Producto;
import dominio.xml.productsByCategories.XMLProductsInfo;

public class createProductInfo extends ActionSupport{
	

	private static final long serialVersionUID = 1L;
	private Long owner_id;
	private Long product_id;
	private XMLProductsInfo xmlproduct;
	ByteArrayInputStream fileStream;
	private String fileContentType;
	private String fileName;
	
	public String execute() throws SQLException{
		
		Producto pro = null;
		pro = Producto.read(product_id, false);
		
		if(pro!=null){
			
			xmlproduct = new XMLProductsInfo(
				pro.getId(),
				pro.getName(),
				pro.getPrecio(),
				pro.getStock(),
				pro.getDescripcion()
			);
			
		}else{
			xmlproduct = new XMLProductsInfo();
		}
		
		/*JAXBContext jc;
		try {
			jc = JAXBContext.newInstance(XMLProductsInfo.class);
			Marshaller marshaller = jc.createMarshaller();
			marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_ENCODING, "utf-8");
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			marshaller.marshal((XMLProductsInfo)xmlproduct, System.out);
			
		} catch (JAXBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println(e.toString());
		}*/
		
		ByteArrayOutputStream productInfoArray;
		try {
			productInfoArray = JAXBAgent.marshal(XMLProductsInfo.class,xmlproduct);
			Blob productInfoBlob= new Blob(productInfoArray.toByteArray());
			fileStream = new ByteArrayInputStream(productInfoBlob.getBytes());
		} catch (JAXBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		fileContentType = "application/xml";
		fileName = "ProductInfo.xml";
		
		return SUCCESS;
	}
	
	
	public Long getOwner_id() {
		return owner_id;
	}
	public void setOwner_id(Long owner_id) {
		this.owner_id = owner_id;
	}
	public Long getProduct_id() {
		return product_id;
	}
	public void setProduct_id(Long product_id) {
		this.product_id = product_id;
	}
	public XMLProductsInfo getXmlproduct() {
		return xmlproduct;
	}
	public void setXmlproduct(XMLProductsInfo xmlproduct) {
		this.xmlproduct = xmlproduct;
	}


	public ByteArrayInputStream getFileStream() {
		return fileStream;
	}


	public void setFileStream(ByteArrayInputStream fileStream) {
		this.fileStream = fileStream;
	}


	public String getFileContentType() {
		return fileContentType;
	}


	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}


	public String getFileName() {
		return fileName;
	}


	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
	
	
	
	
	
	

}
